package com.itheima.web;

import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *   异步运行的servlet
 */
@WebServlet(name = "AsyncServlet", asyncSupported = true, urlPatterns = "/async")   // 开启异步支持
public class AsyncServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        long b = System.currentTimeMillis();
        // 开启异步任务
        AsyncContext asyncContext = request.startAsync();
        // 执行业务
        asyncContext.start(() -> doSomething(asyncContext));
        // 打印耗时时间
        System.out.println("async use:" + (System.currentTimeMillis() - b));
    }

    private void doSomething(AsyncContext context) {
        try {
            // 模拟延迟
            Thread.sleep(5000);
            // 模拟业务
            context.getResponse().getWriter().write("async, hello !");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 结束业务
        context.complete();
    }
}